var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// 中间件
const bodyParser = require('body-parser');
const session = require('express-session');

var app = express();


var router = require('./routes');


app.use('/static', express.static(path.join(__dirname, 'static')));
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('express-art-template'));
app.set('view options', {
  debug: process.env.NODE_ENV !== 'production'
});
app.set('view engine', 'html');

// body-parser配置
// parser application/x-www-form-urlencode
app.use(bodyParser.urlencoded({ extended: false}))
// parse application/json
app.use(bodyParser.json())

// session 配置
app.use(session({
  // 配置加密字符串， 会在原有加密的基础上， 拼接起来再次加密
  // 目的防止客户端恶意篡改，提高安全性
  secret: 'keyboard cat',
  resave: false,
  // 无论是否需要 session, 默认给客户端分配session， 如果设置成 false, 只有设置了 session的时候才会给客户端分配session
  saveUninitialized: true
}))

// session默认是内存存储的，服务器一旦重启就会丢失，真正在生产环境session采用持久化存储


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', indexRouter);
//app.use('/users', usersRouter);
app.use(router);

// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//  next(createError(404));
//});
app.use((req, res) => {
  res.render('error/404.html')
})

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
   res.locals.message = err.message;
   res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
   res.status(err.status || 500);
   res.render('error');

 /*  res.status(500).json({
    code: 500,
    msg: err.msg
  }) */
});

module.exports = app;